﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using ESRI.ArcGIS.Client;
using ESRI.ArcGIS.Client.Toolkit;
using ESRI.ArcGIS.Client.Symbols;
using ESRI.ArcGIS.Client.Geometry;
using ESRI.ArcGIS.Client.Graphics;
using ESRI.ArcGIS.Client.Tasks;
using System.ServiceModel;
using System.Threading;
using System.Windows.Browser;
using SilverlightApplication.ServiceReference1;

namespace SilverlightApplication
{
    public partial class MainPage : UserControl
    {

        public bool isShiftMapFlag;
        public bool navigationToolbarVisual;
        GraphicsLayer graphicsLayer;
        GraphicsLayer graphicsLayerflare;
        QueryTask queryTask;
        private Geoprocessor DiffereTask = null;
        ESRI.ArcGIS.Client.Tasks.FeatureSet featureSetQuery;//图层要素集 查询选择对象
        private int SelectedCityindex;
        public static string SelectedCityname;
        public string telNumber = null;        //存放被点击村对象的电话号码
        
        //接收到ASP.NET页面传送过来的QueryString值
       // IDictionary<String, String> paras = HtmlPage.Document.QueryString;
        public MainPage()
        {
            InitializeComponent();
            //ShowQueryString();
            string uid = HtmlPage.Document.Cookies.Split('=')[1];
            GetUserAuth(uid);
           // GetOnlineStatus();
           

        }

        /// <summary>
        /// 服务中取值
        /// </summary>
        private void GetUserAuth(string uid)
        {
          WebServiceForMapSoapClient wsClient = new WebServiceForMapSoapClient();
          wsClient.GetUserAuthCompleted+=new EventHandler<GetUserAuthCompletedEventArgs>(wsClient_GetUserAuthCompleted);
          wsClient.GetUserAuthAsync(uid);
            
        }
     
        void wsClient_GetUserAuthCompleted(object sender, GetUserAuthCompletedEventArgs e)
        {

            for (var i = 0; i < e.Result.Count; i++)
            {
                SelectedCity.Items.Add(e.Result[i]);
            }

            SelectedCity.DisplayMemberPath = "Name";
          //  SelectedCity.Items.Add("中牟县");
            
            
           
        }

        /// <summary>
        /// 改变下拉框 重新加载数据 渲染地图
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        
        private void SelectedCity_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            graphicsLayer = myMap.Layers["MyGraphicsLayer"] as GraphicsLayer;
            graphicsLayer.Graphics.Clear();
            
            string name = (SelectedCity.SelectedItem as UserAuth).Name;
            string value = (SelectedCity.SelectedItem as UserAuth).OrganId;
            //string name = "中牟县";
            //string value ="100002";
            //渲染1绿色，0红色
            GetOnlineStatus(name, value);
            ClipMaps(name, value);

        }

#region 点图层渲染

        public void ClipMaps(string name,string value)
        {
            
            query = new ESRI.ArcGIS.Client.Tasks.Query()
            {
                //Geometry = myMap.Extent,
                ReturnGeometry = true,
                OutSpatialReference = myMap.SpatialReference
            };
            query.OutFields.Add("*");
            int length = value.Length;
            switch (length)
            {
                case 2:
                    query.Where = "所属省 = "+ name;
                    ESRI.ArcGIS.Client.Tasks.QueryTask queryTask = new ESRI.ArcGIS.Client.Tasks.QueryTask("http://192.168.1.73/ArcGIS/rest/services/map3/MapServer/9");
                    queryTask.ExecuteCompleted += QueryTask_ExecuteCompleted;
                    queryTask.ExecuteAsync(query);
                    break;
                case 4:
                    query.Where = "所属市 = "+ name;
                    ESRI.ArcGIS.Client.Tasks.QueryTask queryTask1 = new ESRI.ArcGIS.Client.Tasks.QueryTask("http://192.168.1.73/ArcGIS/rest/services/map3/MapServer/7");
                    queryTask1.ExecuteCompleted += QueryTask_ExecuteCompleted;
                    queryTask1.ExecuteAsync(query);
                    break;
                case 6:
                    query.Where = "NAME="+ name;
                    ESRI.ArcGIS.Client.Tasks.QueryTask queryTask2 = new ESRI.ArcGIS.Client.Tasks.QueryTask("http://192.168.1.73/ArcGIS/rest/services/map3/MapServer/10");
                    queryTask2.ExecuteCompleted += QueryTask_ExecuteCompleted;//此处有问题
                    queryTask2.ExecuteAsync(query);
                    break;
                default:
                    break;
            }
        }

        private void QueryTask_ExecuteCompleted(object sender, ESRI.ArcGIS.Client.Tasks.QueryEventArgs args)
        {
            ESRI.ArcGIS.Client.Tasks.FeatureSet featureSet = args.FeatureSet;
            featureSetQuery = args.FeatureSet;
            this.myMap.ZoomTo(featureSet.Features[0].Geometry);
        }


        /// <summary>
        /// 获取和下拉框对应的数据
        /// </summary>
        private void GetOnlineStatus(string name,string value)
        {
            WebServiceForMapSoapClient wsClient = new WebServiceForMapSoapClient();
              wsClient.GetOnlineStatusCompleted +=new EventHandler<GetOnlineStatusCompletedEventArgs>(wsClient_GetOnlineStatusCompleted);
              wsClient.GetOnlineStatusAsync(name, value);
        }

        /// <summary>
        /// 获取数据后，渲染图层
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void wsClient_GetOnlineStatusCompleted(object sender,GetOnlineStatusCompletedEventArgs e)
        {
            if (e.Result.Count > 0)
            {
                for (int i = 0; i < e.Result.Count; i++)
                {
                    double pointx = (double)(e.Result[i].ELng);
                    double pointy = (double)(e.Result[i].ELat);
                    Graphic graphiconline = new Graphic();
                    graphiconline.Geometry = new MapPoint(pointx, pointy);
                    if (e.Result[i].EOnline.ToString() == "1")
                    {
                        graphiconline.Symbol = LayoutRoot.Resources["DefaultMarkerSymbol2"] as Symbol;
                        //graphiconline.Attributes["状态"] = "在线";
                    }
                    else if (e.Result[i].EOnline.ToString() == "0")
                    {
                        graphiconline.Symbol = LayoutRoot.Resources["DefaultMarkerSymbol"] as Symbol;
                        //graphiconline.Attributes["状态"] = "离线";
                    }
                    graphiconline.Attributes["NAME"] = e.Result[i].EVillage.ToString();

                    graphicsLayer.Graphics.Add(graphiconline);

                }
                MyMapTip.GraphicsLayer = graphicsLayer;
            }
            else
            {
               //提示没有符合条件的数据
            }
        }

#endregion

#region 点击地图点 处理对应事件
        /// <summary>
        /// 鼠标点击事件，弹出发信息的框  要获取对应点的电话号码 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void myMap_MouseClick(object sender, Map.MouseEventArgs e)
        {
            queryTask = new QueryTask("http://192.168.1.73/ArcGIS/rest/services/map3/MapServer/0");
            queryTask.ExecuteCompleted += QueryTask_ExecuteCompletedleftclick;
            //graphicsLayer.Graphics.Clear();

            Query query = new Query()
            {
                Geometry = Expand(myMap.Extent, e.MapPoint, 0.02),
                ReturnGeometry = true,
                OutSpatialReference = myMap.SpatialReference
            };
            query.OutFields.Add("*");
            queryTask.ExecuteAsync(query);
        }

        /// <summary>
        /// 确定点的范围 为了点击方便
        /// </summary>
        /// <param name="mapExtent"></param>
        /// <param name="point"></param>
        /// <param name="pct"></param>
        /// <returns></returns>
        private Envelope Expand(Envelope mapExtent, MapPoint point, double pct)
        {
            return new Envelope(
                point.X - mapExtent.Width * (pct / 2), point.Y - mapExtent.Height * (pct / 2),
                point.X + mapExtent.Width * (pct / 2), point.Y + mapExtent.Height * (pct / 2))
                {
                    SpatialReference = mapExtent.SpatialReference
                };
        }

        /// <summary>
        /// //左键单击某一个点后的QueryTask_ExecuteCompletedleftclick  
       /// </summary>
       /// <param name="sender"></param>
       /// <param name="args"></param>
        private void QueryTask_ExecuteCompletedleftclick(object sender, ESRI.ArcGIS.Client.Tasks.QueryEventArgs args)
        {
            ESRI.ArcGIS.Client.Tasks.FeatureSet featureSet = args.FeatureSet;
            //GetData();
            graphicsLayerflare = myMap.Layers["MyGraphicsLayerflare"] as GraphicsLayer;
            graphicsLayerflare.Graphics.Clear();
            //MyMapTip.GraphicsLayer = graphicsLayer;
            if (featureSet != null && featureSet.Features.Count > 0)
            {
                foreach (Graphic feature in featureSet.Features)
                {
                    feature.Symbol = LayoutRoot.Resources["SelectMarkerSymbol"] as Symbol;
                    graphicsLayerflare.Graphics.Add(feature);
                    feature.MouseLeftButtonDown += new MouseButtonEventHandler(Feature_MouseLeftButtonDown);
                    feature.MouseLeftButtonUp += new MouseButtonEventHandler(Feature_MouseLeftButtonUp);
                }
            }
        }


        /// <summary>
        /// 启用鼠标弹起事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void Feature_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            e.Handled = true;
        }

        /// <summary>
        /// 位弹出框提取信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void Feature_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            //鼠标左键，显示ToolTip信息  
            Graphic g = sender as Graphic;
            if (g != null)
            {
                //弹出对应的提示信息   
                MapTip tip = new MapTip(g.Attributes["NAME"].ToString(), telNumber);
                tip._placeName = g.Attributes["NAME"].ToString();
                tip._UserTel = telNumber;
                Point p = e.GetPosition(LayoutRoot);
                p.X = p.X;
                p.Y = p.Y;
                tip.Show(p);
            }
        }

       

       //处理 “发送” 和“取消” 按钮的事件 =============================

#endregion
#region
        //定位到村模块
        /// <summary>
        ///定位查询查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void QueryButton_Click(object sender, RoutedEventArgs e)
        {
            QueryTask queryTask =
               new QueryTask("http://192.168.1.73/ArcGIS/rest/services/map3/MapServer/0");
            queryTask.ExecuteCompleted += QueryTask_ExecuteCompletedposition;
            queryTask.Failed += QueryTask_Failed;

            ESRI.ArcGIS.Client.Tasks.Query query = new ESRI.ArcGIS.Client.Tasks.Query();
            query.Text = this.CountyName.SelectedItem.ToString();
            query.OutFields.Add("*");
            queryTask.ExecuteAsync(query);
        }

        /// <summary>
        /// 定位查询完后所激发的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        void QueryTask_ExecuteCompletedposition(object sender, ESRI.ArcGIS.Client.Tasks.QueryEventArgs args)
        {
            GraphicsLayer graphicsLayer = myMap.Layers["MyGraphicsLayerflare"] as GraphicsLayer;
            graphicsLayer.Graphics.Clear();
            FeatureSet featureSet = args.FeatureSet;
            if (featureSet != null && featureSet.Features.Count > 0)
            {
                foreach (Graphic feature in featureSet.Features)
                {
                    if (feature.Attributes["所属县"].ToString() == SelectedCity.SelectedItem.ToString())
                    {

                        feature.Symbol = LayoutRoot.Resources["SelectMarkerSymbol"] as ESRI.ArcGIS.Client.Symbols.Symbol;
                        graphicsLayer.Graphics.Add(feature);
                        myMap.PanTo(feature.Geometry);
                        break;
                    }
                }
            }
            else
            {
                MessageBox.Show("No features returned from query");
            }
        }

        /// <summary>
        /// 查询失败 处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void QueryTask_Failed(object sender, TaskFailedEventArgs args)
        {
            MessageBox.Show("Query execute error: " + args.Error);
        }

 #endregion  常用工具处理
        //Toolbar点击
        private void Toolbar_ToolbarItemClicked(object sender, ESRI.ArcGIS.Client.Toolkit.SelectedToolbarItemArgs e)
        {
            switch (e.Index)
            {
                case 0:
                    if (this.SelectedCity.Visibility == Visibility.Visible)
                    {
                        this.SelectedCity.Visibility = Visibility.Collapsed;
                    }
                    else
                    {
                        this.SelectedCity.Visibility = Visibility.Visible;
                    }
                    return;

                case 1:
                    List<string> selectedGraPoint = new List<string>();
                    if (graphicsLayer.Graphics.Count > 0)
                    {
                        for (int i = 0; i < graphicsLayer.Graphics.Count; i++)
                        {
                            selectedGraPoint.Add(graphicsLayer.Graphics[i].Attributes["NAME"].ToString());
                        }
                        this.CountyName.ItemsSource = selectedGraPoint;
                    }
                    else
                    {
                        MessageBox.Show("所选地区没有任何村庄，为选中任何地区！");
                    }
                    if (this.ResultsDisplayCanvas.Visibility == Visibility.Visible)
                    {
                        this.ResultsDisplayCanvas.Visibility = Visibility.Collapsed;
                    }
                    else
                    {
                        this.ResultsDisplayCanvas.Visibility = Visibility.Visible;
                    }
                    return;

                case 2:
                    return;

                case 3:
                    return;

                case 4:
                    Application.Current.Host.Content.IsFullScreen = !Application.Current.Host.Content.IsFullScreen;
                    return;

            }
        }

        private void CountyName_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //CountyName.Tag= CountyName.SelectedItem.ToString();
        }
        public ESRI.ArcGIS.Client.Tasks.Query query;

    }

}
